package com.lmy.springCloud.controller;

import com.lmy.springCloud.entity.Member;
import com.lmy.springCloud.service.MemberOpenFeignService;
import com.lmy.springCloud.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class MemberNacosConsumerController {

    /*
        http://member-service-nacos-provider 填写的就是要调用的服务注册到NacosServer的服务名
        这里使用小写
     */
    private static final String MEMBER_NACOS_SERVICE_NAME = "http://member-service-nacos-provider";

    //装配RestTemplate
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private MemberOpenFeignService memberOpenFeignService;

    //通过openFeign实现远程调用
    @GetMapping(value = "/openFeign/consumer/getMemberById/{id}")
    public Result<Member> getMemberOpenFeignById(@PathVariable(value = "id") Long id) {
        log.info("调用方式是 openFeign..");
        //使用openFeign接口方式远程调用
        return memberOpenFeignService.getMemberById(id);
    }

    @PostMapping(value = "/nacos/consumer/saveMember")
    public Result saveMember(Member member) {
        log.info("service_consumer_member={}", member);
        //请求会员中心微服务的/saveMember
        //postForObject 以对象的方式发送请求，即json对象
        Result result = restTemplate.postForObject(MEMBER_NACOS_SERVICE_NAME + "/saveMember",
                member, Result.class);
        return result;
    }

    @GetMapping(value = "/nacos/consumer/getMemberById/{id}")
    public Result getMemberById(@PathVariable("id") Long id) {
        //请求会员中心微服务的//getMemberById/{id}
        //这里通过restTemplate+ribbon调用服务提供模块的接口，就是一个远程调用即rpc(remote procedure call)
        Result result = restTemplate.getForObject(MEMBER_NACOS_SERVICE_NAME + "/getMemberById/" + id, Result.class);
        return result;
    }
}
